# == Schema Information
#
# Table name: dorms
#
#  id               :bigint           not null, primary key
#  electric_balance :decimal(, )
#  name             :string
#  created_at       :datetime         not null
#  updated_at       :datetime         not null
#  hydropower_id    :integer
#
# Indexes
#
#  index_dorms_on_hydropower_id  (hydropower_id)
#
class Dorm < ApplicationRecord
  belongs_to :hydropower
  has_many :dorm_users, :dependent => :destroy

  def avatag_total
    total_amount = self.dorm_users.sum(:pay_balance)
    # 平均
    num1 = (self.hydropower.water_balance / self.hydropower.dorm_users.sum(:day_count))
    day_count_electric = (self.electric_balance / self.dorm_users.sum(:day_count))
    total = []
    self.dorm_users.where('pay_balance > ?', 0).each do |dorm_user|
      shenyu = 0
      shenyu += (dorm_user.pay_balance - (num1 * dorm_user.day_count))
      shenyu = (shenyu - (day_count_electric * dorm_user.day_count))
      total << shenyu

    end
    total.sum
  end
end
